import { useState, useEffect } from 'react'
import { Card, Button, Table, Tag, message, Popconfirm, Drawer, Form, Input, DatePicker, Radio } from 'antd'
import { getCouponrList, addCouponr, editCoupon, delCouponr, invalidCouponr } from '@/api/coupon'

const { RangePicker } = DatePicker
const { TextArea } = Input
function Coupon() {
  const [userList, setuserlList] = useState([])
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  useEffect(() => {
    getList()
  }, [page])
  const getList = () => {
    getCouponrList(page).then(res => {
      if (res.status === 200) {
        console.log(res.data)
        let data = res.data.list.map((item: any) => {
          item.statusText = formatStatus(item)
          return item
        })
        setuserlList(data)
        setTotal(res.data.totalCount)
      }
    })
  }
  const switchChange = (id: number) => {
    invalidCouponr(id).then(res => {
      if (res.status === 200) {
        getList()
        message.success('修改成功')
      } else {
        message.error('修改失败')
      }
    })
  }
  const delLevel = (id: number) => {
    delCouponr(id).then(res => {
      if (res.status === 200) {
        getList()
        message.success('删除成功')
      } else {
        message.error('删除失败')
      }
    })
  }
  const formatStatus = (row: any) => {
    let s = '领取中'
    let start_time = new Date(row.start_time).getTime()
    let now = new Date().getTime()
    let end_time = new Date(row.end_time).getTime()
    if (start_time > now) {
      s = '未开始'
    } else if (end_time < now) {
      s = '已结束'
    } else if (row.status == 0) {
      s = '已失效'
    }
    return s
  }

  // 添加修改弹框
  const [openDrawer, setOpenDrawer] = useState(false)
  const [editId, setEditId] = useState(0)
  const [type, setType] = useState(0)
  const [form] = Form.useForm()

  const addBtn = () => {
    setStartTime(Date.now())
    setEndTime(Date.now())
    setEditId(0)
    setOpenDrawer(true)
    form.resetFields()
  }
  const editBtn = (data: any) => {
    setOpenDrawer(true)
    setEditId(data.id)
    form.setFieldsValue({
      name: data.name,
      type: data.type,
      value: data.value,
      total: data.total,
      min_price: data.min_price,
      order: data.order,
      desc: data.desc,
      time: data.start_time
    })
    setStartTime(data.start_time)
    setEndTime(data.end_time)
  }
  const saveAddLevelBtn = () => {
    form.validateFields().then(values => {
      let data = { ...values, start_time, end_time }
      if (editId !== 0) {
        editCoupon(editId, data).then(res => {
          if (res.status === 200) {
            message.success('修改成功')
            getList()
            setOpenDrawer(false)
          }
        })
      } else {
        console.log(data)
        addCouponr(data).then(res => {
          if (res.status === 200) {
            message.success('添加成功')
            getList()
            setOpenDrawer(false)
          }
        })
      }
    })
  }
  const [start_time, setStartTime] = useState(Date.now())
  const [end_time, setEndTime] = useState(Date.now())

  // 获取选择的开始时间和结束时间
  const onTimeChange = (dates: any, dateStrings: any) => {
    if (dates) {
      const [start, end] = dates
      console.log(dateStrings)
      setStartTime(new Date(start).getTime())
      setEndTime(new Date(end).getTime())
    }
  }
  // 禁用早于当前时间的日期
  const disabledDate = (current: any) => {
    const now = new Date()
    now.setHours(0, 0, 0, 0)
    // 比较日期，只允许选择今天或未来的日期
    return current && current.valueOf() < now.getTime()
  }
  // 禁用时间
  const disabledTime = (current: any) => {
    if (!current) {
      return {}
    }

    const now = new Date()

    // 如果选择的是当前日期，禁用当前时间之前的小时和分钟
    if (current.isSame(now, 'day')) {
      const currentHour = now.getHours()
      const currentMinute = now.getMinutes()
      return {
        disabledHours: () => Array.from({ length: 24 }, (_, i) => i).filter(hour => hour < currentHour),
        disabledMinutes: (selectedHour: any) => {
          if (selectedHour === currentHour) {
            return Array.from({ length: 60 }, (_, i) => i).filter(minute => minute < currentMinute)
          }
          return []
        }
      }
    }

    // 如果选择的不是今天，不限制时间
    return {}
  }
  const btn = (
    <div style={{ textAlign: 'right' }}>
      <Button type='primary' size='large' onClick={saveAddLevelBtn}>
        提交
      </Button>
      <Button
        size='large'
        style={{ marginLeft: '15px' }}
        onClick={() => {
          setOpenDrawer(false)
        }}
      >
        取消
      </Button>
    </div>
  )
  const columns = [
    {
      title: '优惠券名称',
      width: '350px',
      render: (data: any) => (
        <div style={{ padding: '5px 15px ' }} className={data.statusText !== '领取中' ? 'bgGrey' : 'bgActive'}>
          <p>{data.name}</p>
          <p>
            {data.start_time} - {data.end_time}
          </p>
        </div>
      )
    },
    {
      title: '状态',
      render: (data: any) => <>{<p>{data.statusText}</p>}</>
    },
    {
      title: '优惠',
      render: (data: any) => (
        <>
          <div>
            {data.type === 0 && (
              <span>
                满 {data.min_price}减{Number(data.value).toFixed(0)}
              </span>
            )}
            {data.type !== 0 && (
              <span>
                满 {data.min_price}打{Number(data.value).toFixed(0)}折
              </span>
            )}
          </div>
        </>
      )
    },
    {
      title: '发放数量',
      dataIndex: 'total',
      key: 'total'
    },
    {
      title: '已使用',
      dataIndex: 'used',
      key: 'used'
    },
    {
      title: '操作',
      render: (data: any) => (
        <div className='flex2 centerFlex' style={{ maxWidth: '150px' }}>
          {data.statusText === '领取中' ? (
            <Popconfirm
              title='注意'
              description='你确认要让优惠券失效吗？'
              onConfirm={() => {
                switchChange(data.id)
              }}
              okText='确认'
              cancelText='取消'
            >
              <Tag color='gold'>失效</Tag>
            </Popconfirm>
          ) : (
            <div>
              {data.statusText === '未开始' && (
                <Tag
                  color='lime'
                  onClick={() => {
                    editBtn(data)
                  }}
                >
                  修改
                </Tag>
              )}
              <Popconfirm
                title='注意'
                description='你确认要删除该等级吗？'
                onConfirm={() => {
                  delLevel(data.id)
                }}
                okText='确认'
                cancelText='取消'
              >
                <Tag color='red'>删除</Tag>
              </Popconfirm>
            </div>
          )}
        </div>
      )
    }
  ]
  return (
    <>
      <Card>
        <Button onClick={addBtn}>新增</Button>
        <Table
          columns={columns}
          dataSource={userList}
          rowKey='id'
          pagination={{ total }}
          onChange={(e: any) => {
            setPage(e.current)
          }}
        />
      </Card>
      <Drawer
        title={editId === 0 ? '新增会员等级' : '修改会员等级'}
        onClose={() => {
          setOpenDrawer(false)
        }}
        open={openDrawer}
        footer={btn}
        width='35%'
      >
        <Form
          form={form}
          labelAlign='right'
          labelCol={{ span: 5 }} // 标签占据的栅格数
          wrapperCol={{ span: 21 }} // 输入框占据的栅格数
        >
          <Form.Item name='name' label='优惠券名称' rules={[{ required: true, message: '请输入优惠券名称' }]}>
            <Input placeholder='请输入优惠券名称' />
          </Form.Item>
          <Form.Item name='type' label='类型' initialValue={type}>
            <Radio.Group
              onChange={e => {
                setType(e.target.value)
              }}
              value={type}
            >
              <Radio value={0}>满减</Radio>
              <Radio value={1}>折扣</Radio>
            </Radio.Group>
          </Form.Item>
          {type === 0 ? (
            <Form.Item name='value' label='面值' rules={[{ required: true, message: '请输入面值' }]} initialValue={0}>
              <Input placeholder='请输入面值' addonAfter='元' />
            </Form.Item>
          ) : (
            <Form.Item name='value' label='折扣' rules={[{ required: true, message: '请输入折扣' }]} initialValue={0}>
              <Input placeholder='请输入折扣' addonAfter='折' />
            </Form.Item>
          )}
          <Form.Item name='total' label='发行数量' rules={[{ required: true, message: '请输入发行数量' }]} initialValue={100}>
            <Input placeholder='请输入发行数量' />
          </Form.Item>
          <Form.Item name='min_price' label='最低使用' rules={[{ required: true, message: '请输入最低使用多少元!' }]} initialValue={1}>
            <Input placeholder='请输入最低使用多少元' addonAfter='元' />
          </Form.Item>
          <Form.Item name='order' label='排序' rules={[{ required: true, message: '请输入排序' }]} initialValue={50}>
            <Input placeholder='请输入排序' />
          </Form.Item>
          <Form.Item name='time' label='活动时间' rules={[{ required: true, message: '请选择时间' }]}>
            {/* start_time end_time */}
            <RangePicker showTime disabledDate={disabledDate} disabledTime={disabledTime} onChange={onTimeChange} />
          </Form.Item>
          <Form.Item name='desc' label='描述'>
            <TextArea rows={4} placeholder='请输入描述内容' maxLength={6} />
          </Form.Item>
        </Form>
      </Drawer>
    </>
  )
}
export default Coupon
